﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OgilvyOne.UKNow.BLL;
using OgilvyOne.UKNow.Model;
using ECCIT.Extension.Weibo_v2.Common;
using ECCIT.Extension.Weibo_v2.Model;
using OgilvyOne.UKNow.Utility;

public partial class SinaM : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                string token = Request.QueryString["access_token"] != null ? Request.QueryString["access_token"] : "";
                string uid = Request.QueryString["uid"];
                string apiUrl = "https://api.weibo.com/2/users/show.json?";
                apiUrl += RFC3986Encoder.Encode("access_token") + "=" + RFC3986Encoder.Encode(token);
                apiUrl += "&" + RFC3986Encoder.Encode("uid") + "=" + RFC3986Encoder.Encode(uid);
                //string url = String.Format("access_token={0}&uid={1}", token, uid);
                GetDocByURL gd = new GetDocByURL(apiUrl);
                string ii = gd.GetDoc();
                WeiboUserInfo userInfo = JsonSerializationHelper.JsonToObject<WeiboUserInfo>(ii);
                if (userInfo != null)
                    reg(userInfo);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }

    private void reg(WeiboUserInfo userInfo)
    {
        AccountController acl = new AccountController(Convert.ToInt32(Request.Form["langid"]));
        string uid = userInfo.ID.ToString();

        MemberMappBLL mmbll = new MemberMappBLL();
        MemberBLL mbll = new MemberBLL(Convert.ToInt32(Request.Form["langid"]));
        MemberModel mm = new MemberModel();
        if (!mmbll.isExit(uid))
        {
            string name = userInfo.ScreenName;

            mm.Name = name;
            mm.InsertTime = DateTime.Now;
            mm.LastLoginTime = DateTime.Now;
            int? mebid = (mbll.Save(mm).ReturnObject as MemberModel).ID;
            MemberMappMod mmm = new MemberMappMod();
            mmm.Exid = uid;
            mmm.UKid = Convert.ToInt32(mebid);
            mmm.Mtype = 2;
            mmbll.add(mmm);

            acl.ProcessLogin(mmm.UKid);
            Response.Write("2");
        }
        else
        {
            int ukid = Convert.ToInt32(mmbll.getUkid(uid));
            acl.ProcessLogin(ukid);
            string pass = mbll.getMemberByID(ukid).Password;
            if (pass != null)
            {
                if (pass.Trim().Length > 0)
                {
                    Response.Write("3");
                }
                else
                {
                    Response.Write("2");
                }
            }
            else
            {
                Response.Write("2");
            }
        }
    }
}